from machine import I2C,Pin
import network,time,usocket
from ssd1306 import SSD1306_I2C #从 ssd1306 模块中导入 SSD1306_I2C 子模块

i2c = I2C(sda=Pin(45), scl=Pin(46))
#OLED 显示屏初始化：128*64 分辨率, I2C 地址是 0x3c
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)

led_gpio = 48
p38= Pin(led_gpio,Pin.OUT)

wlan=network.WLAN(network.STA_IF)


p2= Pin(2,Pin.OUT)

def oledShow(message):
    oled.fill(0)
    oled.show()
    oled.text(message[0], 0, 0) #写入第 1 行内容
    oled.text(message[1], 0, 10,1) #写入第 1 行内容
    oled.text(message[2], 0, 20,1) #写入第 1 行内容
    oled.text(message[3], 0, 30,1) #写入第 1 行内容
    oled.show() #OLED 执行显示

def oledMessage(message):
    oled.fill(0)
    oled.show()
    oled.text(message, 0, 0) #写入第 1 行内容
    oled.show() #OLED 执行显
    

def wifiConnect():
    wlan.active(True)
    startTime=time.time()
    if not wlan.isconnected():
        wlan.connect(ssid,password)
        print("正在连接网络")
        while not wlan.isconnected():
            print(".")
            p38.value(0)
            time.sleep_ms(200)
            p38.value(1)
            time.sleep_ms(200)
            if time.time()-startTime>10:
                print("连接网络超时失败，请重试@")
                p38.value(1)
                break
            

def web_page():
    if  p2.value()==1:
        gpio_state='开'
    else:
        gpio_state='关'
    htmltxt ='''
    <!DOCTYPE html>
    <html lang="zh-CN">
        <head>
            <meta charset="UTF-8">
        </head>
        <body>
            <div class="container">
                <div class="header">
                    <h1>设备远程控制器</h1>
                </div>
                
                <div class="control-panel">
                    <div class="status">
                        当前状态: <span id="">''' + gpio_state + '''</span>
                    </div>
                    
                    <p><a href="/?led=on"> <button class="button">开灯</button></a></p>
                    <p><a href="/?led=off"> <button class="button">关灯</button></a></p>
                </div>
                
                <div class="footer">
                    <p>设备控制界面 &copy; 2023</p>
                </div>
            </div>
         </body>
     </html>
    '''
    return htmltxt


if __name__=="__main__":
    # connect wifi
    wlan.active(True)
    nwifi=wlan.scan()
    print("可用网络",nwifi)
    ssid = "Lanmei"
    password="Lanmei666"
    wifiConnect()
    
    if wlan.isconnected():
        print("---------")
        print("连接到网络：",ssid)
        print("网络配置信息")
        print(wlan.ifconfig())
        # show oled wifi
        oledShow(wlan.ifconfig())
        
    else:
        pass
        
    
    ip = "192.168.1.4"
    port =10000
    
    if wlan.isconnected():
        # 创建基于TCP的流式套接字 ,并且在80端口监听最多5个连接
        skt = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
        skt.bind(('',80))
        skt.listen(5)
       
        while True:
            client,addr = skt.accept()
            addr =str(addr)
            print("get client(ip,port) :%s"%addr)
            
            req = client.recv(1024)
            req = str(req)
            print("get client request contnt:%s"%req)
            
            args_on = req.find('/?led=on')
            args_off = req.find('/?led=off')
            
            
            oledMessage(req)
            if args_on >0:
               p2.value(1)
            elif args_off>0:
               p2.value(0) 
            
               
            time.sleep_ms(500)
            
            # 推送页面数据到客户端
            print("---------")
            client.send('http/1.1 200 OK\n')
            client.send('Content-Type: text/html\n')
            client.send('Connection: close\n')
            resp = web_page()
            client.send(resp)
            client.close()
            
        
        
        
        
        

